package com.epam.web_project.bank.command.customer_commands;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.epam.web_project.bank.command.Command;
import com.epam.web_project.bank.dao.account_dao.AccountDAO;
import com.epam.web_project.bank.dao.factory.MySQLDAOFactory;
import com.epam.web_project.bank.db.ConnectionPool;
import com.epam.web_project.bank.entity.Account;
import com.epam.web_project.bank.entity.Customer;
import com.epam.web_project.bank.util.AppPropertiesLoader;

public class BlockAccountCommand implements Command {
	private static AppPropertiesLoader props = AppPropertiesLoader
			.getInstance();

	@Override
	public String execute(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		Customer customer = (Customer) session.getAttribute("customer");
		String role = "";
		if (customer != null) {
			role = customer.getRole();
			if ("customer".equals(role)) {
				return executeCustomer(request, session);
			} else if ("admin".equals(role)) {
				return executeAdmin(request, session);
			} else { //no role - go to login page
				return props.getProperty("login_page");
			}
		} else { //no customer - go to login page
			return props.getProperty("login_page");
		}
	}

	private String executeCustomer(HttpServletRequest request,
			HttpSession session) {
		String resPage = props.getProperty("show_main_command");
		if (request.getParameter("accId").equals("")) {
			return resPage;
		}
		Account account = new Account();
		account.setId(Integer.valueOf(request.getParameter("accId")));
		MySQLDAOFactory daoFactory = new MySQLDAOFactory();
		daoFactory.setConnectionPool(ConnectionPool.getInstance());
		AccountDAO accountDAO = daoFactory.getAccountDAO();
		String message = accountDAO.block(account);
		session.setAttribute("message", message);
		return resPage;
	}

	private String executeAdmin(HttpServletRequest request, HttpSession session) {
		String resPage = props.getProperty("show_working_accounts");
		if (request.getParameter("accId").equals("")) {
			return resPage;
		}
		Account account = new Account();
		account.setId(Integer.valueOf(request.getParameter("accId")));
		MySQLDAOFactory daoFactory = new MySQLDAOFactory();
		daoFactory.setConnectionPool(ConnectionPool.getInstance());
		AccountDAO accountDAO = daoFactory.getAccountDAO();
		String message = accountDAO.block(account);
		session.setAttribute("message", message);
		return resPage;
	}

}
